#define  _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* BuyListNode(LTDateType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (!newnode)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->_data = x;
	newnode->_next = newnode->_prev = NULL;
	return newnode;
}

ListNode* CreateList()
{
	ListNode* phead = BuyListNode(0);
	phead->_next = phead;
	phead->_prev = phead;

	return phead;
}

void ListDestroy(ListNode* phead)
{
	assert(phead);

	ListNode* curr = phead->_next;
	while (curr != phead)
	{
		ListNode* del = curr;
		curr = curr->_next;
		free(del);
	}
	free(phead);
}

void ListInsert(ListNode* pos, LTDateType x)
{
	assert(pos);

	ListNode* posPrev = pos->_prev;
	ListNode* newnode = BuyListNode(x);

	posPrev->_next = newnode;
	newnode->_prev = posPrev;
	newnode->_next = pos;
	pos->_prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	assert(pos->_next != pos);

	ListNode* posPrev = pos->_prev;
	ListNode* posNext = pos->_next;

	posPrev->_next = posNext;
	posNext->_prev = posPrev;
	free(pos);
}

void ListPushBack(ListNode* phead, LTDateType x)
{
	ListInsert(phead, x);
}

void ListPushFront(ListNode* phead, LTDateType x)
{
	ListInsert(phead->_next, x);
}

void ListPopBack(ListNode* phead)
{
	ListErase(phead->_prev);
}

void ListPopFront(ListNode* phead)
{
	ListErase(phead->_next);
}

void ListPrint(ListNode* phead)
{
	printf("phead:");
	ListNode* curr = phead->_next;
	while (curr != phead)
	{
		printf("%d ", curr->_data);
		curr = curr->_next;
	}
	printf("NULL\n");

}